<!DOCTYPE html>
<html lang="en">
<head>
    <title>对话</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <link rel="stylesheet" href="https://cdn.bootcss.com/weui/1.1.2/style/weui.min.css">
    <link rel="stylesheet" href="https://cdn.bootcss.com/jquery-weui/1.2.0/css/jquery-weui.min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/demos.css') }}?t=211">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/jscrollpane1.css') }}?t=12112211">
    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>

    </style>
</head>
<body>

<!--<div class="text">-->
<!--&lt;!&ndash;<div class="talk">&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;<div class="talk_title"><span>对话</span></div>&ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash;<div class="talk_record">&ndash;&gt;-->
<!--&lt;!&ndash;&ndash;&gt;-->

<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--</div>-->

<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
<script src="https://cdn.bootcss.com/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
<script src="https://cdn.bootcss.com/jScrollPane/2.1.3-rc.2/script/jquery.jscrollpane.min.js"></script>
<script src="{{ url_for('static', filename='js/scroll-startstop.events.jquery.js') }}"></script>
<script src="https://cdn.bootcss.com/jquery-weui/1.2.0/js/jquery-weui.min.js"></script>
<script src="{{ url_for('static', filename='js/common.js') }}"></script>
<script>
    var device_name = "{{ device_name }}"
    var talk = {
        record_show_flag: false,
        toggleRecord: function () {
            this.record_show_flag = !this.record_show_flag;
            if (this.record_show_flag) {
                $('#record').css('display', 'flex')
            } else {
                $('#record').css('display', 'none')
            }
        }
    };

    var view_device = {
        gallery_toggle: function (url) {
            console.log(url)
            if (typeof url === 'undefined') {
                $('#gallery').hide()
            } else {
                $('#gallery .weui-gallery__img').css(
                    'background-image',
                    'url(' + url + ')'
                );
                $('#gallery').show()
            }
        }
    }

    var sn = "{{ device_sn }}"
    var openid = "{{ openid }}"
    $(function () {
        if (sn.length == 0) {
            $.alert("注意", "请先绑定设备，然后可以聊天。", function () {
                location.href = "/demo"
            });
        } else {
            get_msg_list();
        }

        var dshiqi = null;

        //录音播放
        $(".askinput").on("click", ".r_yuyin", function () {
            //先暂停其他的
            $(this).parent(".add_yuyin").siblings().find("audio")[0].pause();
            $(this).parent(".add_yuyin").siblings().find("s").removeClass("bofang");
            var audio = $(this).find("audio")[0],
                time = $(this).data("time");
            if (audio.paused) {
                audio.play(); //audio.play();// 这个就是播放
                $(this).find("s").addClass("bofang");
                dshiqi = setTimeout(function () { //dshiqi是外层定义好的一个变量！
                    $(this).find("s").removeClass("bofang"); //播放完毕去除动画
                }, time * 1000)
            } else {
                audio.pause(); // 这个就是暂停
                $(this).find("s").removeClass("bofang");
                clearTimeout(dshiqi);
            }
        })


        if ($(".askinput").children().length > 1) {
            $(".tijaobtn").removeAttr("disabled");
        } else {
            $(".tijaobtn").attr("disabled", true);
        }

        $(".askinput").on("touchstart", ".deleteicon", function () {
            $(".tip_zhezhao").show();
            $(".g_dialog").show();
        });
        $("#g_delete").on("touchstart", function () {
            $(".tip_zhezhao").hide();
            $(".g_dialog").hide();
            $("#addluyin").show();
            $("#luyin_operate").hide();
        });

        //关闭录音弹层
        $(".bottom_op").on("touchstart", ".closebtn", function () {
            $(".luyin_dialog").hide();
        });

        //弹出录音弹层
        $("#addluyin").on("touchstart", function () {
            $(".luyin_dialog").show();
        });

        //录制完毕按钮操作data-start=0未开始录制，弹出提示，data-start=1录制完毕，回填
        $(".bottom_op").on("touchstart", ".finishbtn", function () {
            var status = $(this).data("start");
            if (status == 0) {
                $(".tip_dialog").show();
                setTimeout(function () {
                    $(".tip_dialog").hide()
                }, 3000)
            } else {
                //录音结束之后状态操作
                $("#addluyin").hide();
                //录音秒数回填，此处后面再写
                $("#luyin_operate").show();
                //录音窗口关闭
                $(".luyin_dialog").hide();
            }
        });

        //录制按钮点击
        $(".lz_operate").on("touchstart", function () {
            $(this).children("s").addClass("l_start");
            $(this).children("span").html("点击结束");
            $(this).prev(".closebtn").hide();
            $(this).next(".finishbtn").hide();
            $(".topstatus").children(".start").show();
            $(".topstatus").children(".notbegin").hide();
        })


    })

    function get_msg_list() {
        var sn = "{{ device_sn }}";
        var data = {"sn": sn};
        $.ajax({
            type: "POST",
            url: "get_msg_list",
            data: data,
            success: function (response) {
                if (response.err == 0 && response.list.length > 0) {
                    var msg_list = response.list;
                    var arrayLength = msg_list.length;
                    for (var i = 0; i < arrayLength; i++) {
                        add_msg_display(msg_list[i])
                    }
                }
            }
        });
    }

    function get_msg_list_add(data) {
        var sn = "{{ device_sn }}";
        var sn_data = {"sn": sn};
        $.ajax({
            type: "POST",
            url: "get_msg_list",
            data: sn_data,
            success: function (response) {
                if (response.err == 0 && response.list.length > 0) {
                    var msg_list = response.list;
                    var arrayLength = msg_list.length;
                    for (var i = 0; i < arrayLength; i++) {
                        add_msg_display(msg_list[i])
                    }
                    add_msg_display(data);
                }
            }
        });
    }

    function add_msg_display(data) {
        var dateToDis = new Date();
        if (undefined != data.time) {
            dateToDis = new Date(data.time);
        }
        if (data && "0" == data.type) {
            if (undefined != data.sender && data.sender == openid) {
                $("#jp-container").append("<div class=\"talk_recordboxme\">\n" +
                    "                    <div class=\"user\">我</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <h3 style=\"margin-top: 5px; margin-bottom: 5px\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + data.content + "</h3>\n" +
                    "                        <span class=\"talk_time\">" + (dateToDis.toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");
            } else if (undefined != data.sender && data.sender == sn) {
                $("#jp-container").append("<div class=\"talk_recordbox\">\n" +
                    "                    <div class=\"user\">" + device_name + "</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <h3 style=\"margin-top: 5px; margin-bottom: 5px\">&nbsp;&nbsp;" + data.content + "</h3>\n" +
                    "                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");

            }

        } else if (data && "1" == data.type) {
            if (undefined != data.sender && data.sender == openid) {
                /*$("#jp-container").append("<div class=\"talk_recordboxme\">\n" +
                    "                    <div class=\"user\">我</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <h3 style=\"margin-top: 5px; margin-bottom: 5px\">" + data.content + "</h3>\n" +
                    "                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");*/
            } else if (undefined != data.sender && data.sender == sn) {
                $("#jp-container").append("<div class=\"talk_recordbox\">\n" +
                    "                    <div class=\"user\">" + device_name + "</div>\n" +
                    //"                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    //"                    <div class=\"talk_recordtext\">\n" +
                    "                        <audio controls>\n" +
                    "  <source src=\"" + data.content + "\" type=\"audio/mpeg\">\n" +
                    "</audio>" //+
                    /*"<div class=\"r_yuyin\" style=\"width: 76%;\" data-time=\"46\">" +
                    "<audio preload=\"auto\" hidden=\"true\">" +
                    "    <source src=\"{{ url_for('static', filename='images/horse.mp3') }}\" type=\"audio/mpeg\">" +
                    "</audio>" +
                    "<s class=\"bofang\"></s>" +
                    "</div>" +*/
                    //"                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    //"                    </div>\n" +
                    //"                </div>"
                )
                ;

            }

        } else if (data && "2" == data.type) {
            if (undefined != data.sender && data.sender == openid) {
                $("#jp-container").append("<div class=\"talk_recordboxme\">\n" +
                    "                    <div class=\"user\">我</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <h3 style=\"margin-top: 5px; margin-bottom: 5px\">" + data.content + "</h3>\n" +
                    "                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");
            } else if (undefined != data.sender && data.sender == sn) {
                $("#jp-container").append("<div class=\"talk_recordbox\">\n" +
                    "                    <div class=\"user\">" + device_name + "</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <img onclick=\"view_device.gallery_toggle($(this).attr('src'))\"" +
                    "                             src=\"" + data.content + "\"" +
                    "                             style=\"width: 10vw;height: 10vw\"/>" +
                    "                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");

            }

        } else if (data && "7" == data.type) {
            if (undefined != data.sender && data.sender == openid) {
                $("#jp-container").append("<div class=\"talk_recordboxme\">\n" +
                    "                    <div class=\"user\">我</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <h3 style=\"margin-top: 5px; margin-bottom: 5px\">" + data.content + "</h3>\n" +
                    "                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");
            } else if (undefined != data.sender && data.sender == sn) {
                $("#jp-container").append("<div class=\"talk_recordbox\">\n" +
                    "                    <div class=\"user\">" + device_name + "</div>\n" +
                    //"                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    //"                    <div class=\"talk_recordtext\">\n" +
                    "                        <audio controls>\n" +
                    "  <source src=\"http://" + data.content + "\" type=\"audio/mpeg\">\n" +
                    "</audio>" //+
                    /*"<div class=\"r_yuyin\" style=\"width: 76%;\" data-time=\"46\">" +
                    "<audio preload=\"auto\" hidden=\"true\">" +
                    "    <source src=\"{{ url_for('static', filename='images/horse.mp3') }}\" type=\"audio/mpeg\">" +
                    "</audio>" +
                    "<s class=\"bofang\"></s>" +
                    "</div>" +*/
                    //"                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    //"                    </div>\n" +
                    //"                </div>"
                )
                ;

            }

        } else if (data && "6" == data.type) {
            if (undefined != data.sender && data.sender == openid) {
                $("#jp-container").append("<div class=\"talk_recordboxme\">\n" +
                    "                    <div class=\"user\">我</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <h3 style=\"margin-top: 5px; margin-bottom: 5px\">" + data.content + "</h3>\n" +
                    "                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");
            } else if (undefined != data.sender && data.sender == sn) {
                $("#jp-container").append("<div class=\"talk_recordbox\">\n" +
                    "                    <div class=\"user\">" + device_name + "</div>\n" +
                    "                    <div class=\"talk_recordtextbg\">&nbsp;</div>\n" +
                    "                    <div class=\"talk_recordtext\">\n" +
                    "                        <img onclick=\"view_device.gallery_toggle($(this).attr('src'))\"" +
                    "                             src=\"http://" + data.content + "\"" +
                    "                             style=\"width: 10vw;height: 10vw\"/>" +
                    "                        <span class=\"talk_time\">" + ((new Date).toLocaleTimeString()) + "</span>\n" +
                    "                    </div>\n" +
                    "                </div>");

            }

        }
        $('#jp-container').scrollTop($('#jp-container')[0].scrollHeight);
    }


    function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    };

    var e = function (sel) {
        return document.querySelector(sel)
    }
    //var chat_area = e('#id-chat-area')
    var clear_board = function () {
        //chat_area.value = ''

        $("#jp-container").html("");
    }
    var change_title = function () {
        tag = e('#id-room-name')
        tag.innerHTML = "聊天室 - " + current_room
    }


    $('#text_msg').keyup(function (e) {
        if (e.keyCode == 13) {
            send_text()
        }
    });
    var send_text = function () {
        if (parent.socket && true == parent.socket.connected) {

            if ($("#text_msg").val().trim() == '') {
                $.alert('请输入文字');
                return;
            }
            var sn = "{{ device_sn }}"
            var openid = getCookie("openid")
            var content = {'text_str': $("#text_msg").val(), 'sn': sn, 'openid': openid}
            parent.socket.emit('send_text', content, function () {
                //清空输入框
                $("#text_msg").val("")
            })

        } else {
            $.alert('请稍后再试');
        }
    }

    window.onload = function () {

        parent.wx.ready(function () {
            var voice = {
                localId: '',
                serverId: ''
            };
            var startRecord = document.querySelector('#startRecord');
            var stopClearTimeout;
            startRecord.onclick = function () {
                //开始录音
                if (startRecord.innerHTML == '开始') {
                    parent.wx.startRecord({
                        success: function () {
                            startRecord.innerHTML = '停止';
                            //30秒后自动停止;
                            stopClearTimeout = setTimeout(function () {
                                parent.wx.stopRecord({
                                    success: function (res) {
                                        voice.localId = res.localId;
                                        startRecord.innerHTML = '试听';
                                    }
                                });
                            }, 30000);
                        },
                    });
                }

                //结束录音
                if (startRecord.innerHTML == '停止') {
                    parent.wx.stopRecord({
                        success: function (res) {
                            clearTimeout(stopClearTimeout);
                            startRecord.innerHTML = '试听';
                            voice.localId = res.localId;
                        },
                        fail: function (res) {
                            alert(JSON.stringify(res));
                        }
                    });
                }

                //试听音频
                if (startRecord.innerHTML == '试听') {
                    if (voice.localId == '') {
                        alert('请先录制一段声音');
                        return;
                    }
                    parent.wx.playVoice({
                        localId: voice.localId
                    });
                }

            };

            //删除语音,重新录音;
            document.querySelector('#deleteVoice').onclick = function () {
                voice.localId = '';
                startRecord.innerHTML = '开始';
            }

            //确认上传语音
            document.querySelector('#uploadVoice').onclick = function () {
                if (voice.localId == '') {
                    $.alert('请先录制一段声音');
                    return;
                }
                parent.wx.uploadVoice({
                    localId: voice.localId,
                    success: function (res) {
                        voice.serverId = res.serverId;
                        var sn = "{{ device_sn }}"
                        if (undefined != sn) {
                            var openid = getCookie("openid");
                            var content = {'media_id': voice.serverId, 'sn': sn, 'openid': openid}
                            parent.socket.emit('send_voice_msg', content, function () {
                                $.alert('发送成功!');
                                voice.localId = '';
                                startRecord.innerHTML = '开始';
                            })

                            //把微信服务器上的serverId传给后台,后台再通过serverId到微信服务器上把语音保存到自己服务器上
                            /*$.ajax({
                                url: '/upload_voice',//后台接收数据地址
                                dataType: "json",
                                type: 'post',
                                data: {'media_id': voice.serverId, 'sn': sn},
                                success: function (msg) {
                                    if (undefined != msg.err && msg.err == 0) {
                                        $.alert('上传服务器成功!');
                                        voice.localId = '';
                                        startRecord.innerHTML = '开始';
                                    } else {
                                        $.alert('上传服务器失败!');
                                    }
                                },
                                error: function (msg) {
                                    $.alert('上传服务器出错了!');
                                }
                            });*/
                        } else {
                            $.alert('没有产品序列号')
                        }
                    }
                });
            };
        });
    }

</script>

</body>
</html>
